package com.example.demo.controller;

import com.example.demo.dao.entity.Blog;
import com.example.demo.dao.entity.SysUser;
import com.example.demo.service.BlogService;
import com.example.demo.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("sysUser")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    /**
     * 查询用户列表
     * @param model
     * @param sysUser
     * @return
     */
    @GetMapping("/list")
    public String getSysUserList(Model model, SysUser sysUser) {
        List<SysUser> list = null;
        if(sysUser.getLoginName() != null && !"".equals(sysUser.getLoginName() )) {
            list = sysUserService.lambdaQuery()
                    .like(SysUser::getLoginName,sysUser.getLoginName() )
                    .list();
            model.addAttribute("loginName", sysUser.getLoginName() );
        }else{
            list = sysUserService.list();
        }
        model.addAttribute("list", list);
        return "sysUser/list";
    }

    /**
     * 新增用户页面
     * @param model
     * @param sysUser
     * @param id
     * @return
     */
    @GetMapping("addpage")
    public String addpage(Model model, @ModelAttribute SysUser sysUser, @RequestParam(value = "id",required = false) String id){
        if(!StringUtils.isEmpty(id)){
            SysUser byId = sysUserService.getById(id);
            model.addAttribute("sysUser",byId);
        }
        return "sysUser/add";
    }

    @PostMapping(value = {"/add", "/update"}, produces = "application/json")
    public String saveOrUpdate(Model model, SysUser sysUser, Principal principal) {
        String loginName = principal.getName();
        sysUser.setUpdatePerson(loginName);
        if(!StringUtils.isEmpty(sysUser.getPassword())) {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String result = encoder.encode(sysUser.getPassword());
            sysUser.setPassword(result);
        }
        sysUserService.saveOrUpdate(sysUser);
        return getSysUserList(model,sysUser);
    }


    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public String deleteSysUserById( @PathVariable String id) {
        sysUserService.removeById(id);
        return "success";
    }

}
